import {
  clearObject,
  deepCopyObj,
  copyObjBySelf
} from '../../../assets/js/help.js'
export default {
  data() {
    var checkLoginId = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'));
      } else {
        var regexp = /^(?!_)(?!.*?_$)[a-zA-Z0-9_]+$/;
        var result = regexp.test(value);
        if (!result) {
          callback(new Error('用户名仅支持英文字符、数字、下划线（_）组合,且不能以下划线为开头或结尾'));
        } else {
          API.platform_manage.CheckLoginId({
            'loginId': value
          }).then(res => {
            if (res.status == 1) {
              if (res.data) {
                callback();
              } else {
                callback(new Error('此用户名已被占用'));
              }
            } else {
              callback(new Error('验证错误，系统繁忙'));
            }
          }, err => {});
        }
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.operaotrForm.passWord !== '') {
          var regexp = /^[a-zA-Z0-9~!@#$%^&*()_<>]+$/;
          var result = regexp.test(value);
          console.log(result);
          if (result) {
            callback();
          } else {
            callback(new Error('用户密码仅支持英文字符、数字、特殊符号~!@#$%^&*()_<>组合'));
          }
        }
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.operaotrForm.passWord) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var resetvalidatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.pwdForm.newPassWord !== '') {
          var regexp = /^[a-zA-Z0-9~!@#$%^&*()_<>]+$/;
          var result = regexp.test(value);
          console.log(result);
          if (result) {
            callback();
          } else {
            callback(new Error('用户密码仅支持英文字符、数字、特殊符号~!@#$%^&*()_<>组合'));
          }
        }
      }
    };
    var resetvalidatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.pwdForm.newPassWord) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      noAuthText: false,
      bindOperator: {
        operatorId: ""
      },
      pwdForm: {
        name: "",
        oldPassword: "",
        newPassWord: "",
        passWordAgain: "",
        loginId: ""
      },
      operaotrForm: {
        id: null,
        name: "",
        areaName: "",
        areaId: "",
        address: "",
        contactor: "",
        mobile: "",
        email: "",
        tel: "",
        licenseImg: "",
        legalIdentityImg: "",
        licenseImgBase64: "",
        legalIdentityImgBase64: "",
        licenseImgName: "",
        legalIdentityImgName: "",
        companyScale: "0-50",
        briefIntroduction: "",
        bankName: "",
        bankCount: "",
        bankAccountName: "",
        bankAccountName: "",
        settlementMobile: "",
        oldName: ""
      },
      companyScale: [{
        value: '0-50',
        label: '0-50人'
      }, {
        value: '50-100',
        label: '50-100人'
      }, {
        value: '100-500',
        label: '100-500人'
      }, {
        value: '500以上',
        label: '500人以上'
      }],
      licenseImg: [],
      legalIdentityImg: [],
      rules: {
        name: [{
            required: true,
            message: '请输入运营商名称',
            trigger: 'change'
          },
          {
            min: 2,
            max: 50,
            message: '长度在 2 到 50 个字符',
            trigger: 'change'
          }
        ],
        areaName: [{
          required: true,
          message: '请输入区域',
          trigger: 'change'
        }],
        address: [{
            required: true,
            message: '请输入地址',
            trigger: 'change'
          },
          {
            min: 2,
            max: 255,
            message: '长度在 2 到 255 个字符',
            trigger: 'change'
          }
        ],
        contactor: [{
            required: true,
            message: '请输入联系人',
            trigger: 'change'
          },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'change'
          }
        ],
        mobile: [{
            required: true,
            message: '请输入联系人手机',
            trigger: 'change'
          },
          {
            validator(r, v, b) {
              (/^1(3|4|5|7|8)\d{9}$/).test(v) ? b() : b(new Error('手机号码不合法'))
            }
          }
        ],
        email: [{
          min: 0,
          max: 60,
          message: '长度在 0 到 60 个字符',
          trigger: 'change'
        }],
        tel: [{
          min: 2,
          max: 20,
          message: '长度在 2 到 20 个字符',
          trigger: 'change'
        }],
        companyScale: [{
          required: true,
          message: '请选择公司规模',
          trigger: 'change'
        }],
        settlementMobile: [{
            required: true,
            message: '请输入结算联系人手机',
            trigger: 'blur'
          },
          {
            validator(r, v, b) {
              (/^1(3|4|5|7|8)\d{9}$/).test(v) ? b() : b(new Error('手机号码不合法'))
            }
          }
        ],
        loginId: [{
            required: true,
            message: '请输入用户名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'change'
          },
          {
            validator: checkLoginId,
            trigger: 'blur'
          }
        ],
        nickName: [{
          required: true,
          message: '请输入用户昵称',
          trigger: 'change'
        }],
        passWord: [{
            required: true,
            message: '请输入密码',
            trigger: 'change'
          },
          {
            min: 6,
            max: 16,
            message: '长度在 6 到 16 个字符',
            trigger: 'change'
          },
          {
            validator: validatePass,
            trigger: 'blur'
          }
        ],
        passWordAgain: [{
          validator: validatePass2,
          trigger: 'blur'
        }]
      },
      operaotrFormStatus: "",
      pwdRules: {
        oldPassword: [{
            required: true,
            message: '请输入旧密码',
            trigger: 'change'
          },
          {
            min: 6,
            max: 16,
            message: '长度在 6 到 16 个字符',
            trigger: 'change'
          },
        ],
        newPassWord: [{
            required: true,
            message: '请输入新密码',
            trigger: 'change'
          },
          {
            min: 6,
            max: 16,
            message: '长度在 6 到 16 个字符',
            trigger: 'change'
          },
          {
            validator: resetvalidatePass,
            trigger: 'blur'
          }
        ],
        passWordAgain: [{
          validator: resetvalidatePass2,
          trigger: 'blur'
        }],
      }

    }
  },
  created() {
    //this.getList();
  },
  methods: {
    getList() {
      this.getOperatorList(this.searchParams);
    },
    getOperatorList(aparams) { //查询列表
      let self = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      params = $.extend({}, params, aparams);
      API.platform_manage.GetOperatorListData(params)
        .then(res => {
          let data = res.data,
            list = data.rows;
          self.tbodysInfo = list;
          self.total = data.total;
        }, err => {})
    },
    frozenOperator(row) { //绑定运营商
      let self = this;
      this.showDialog("是否确认锁定该下级运营商(" + row.name + ")？", [], function () {
        API.platform_manage.FrozenOperator({
          "id": row.id
        }).then(res => {
          if (res.status == 1) {
            self.getList();
            self.showToast("锁定成功", 1);
          } else {
            self.showToast("锁定失败", 2);
          }
        }, err => {});
      }, "操作提示", function () {
        //取消时不操作
      });
    },
    enableOperator(row) { //开启运营商
      let self = this;
      this.showDialog("是否确认开启该下级运营商(" + row.name + ")？", [], function () {
        API.platform_manage.EnableOperator({
          "id": row.id
        }).then(res => {
          if (res.status == 1) {
            self.getList();
            self.showToast("开启成功", 1);
          } else {
            self.showToast("开启失败", 2);
          }
        }, err => {});
      }, "操作提示", function () {
        //取消时不操作
      });
    },
    delOperator(row) { //删除运营商
      let self = this;
      this.showDialog("是否确认删除该下级运营商(" + row.name + ")？", [], function () {
        API.platform_manage.DelOperator({
          "id": row.id
        }).then(res => {
          if (res.status == 1) {
            self.getList();
            self.showToast("删除成功", 1);
          } else {
            self.showToast("删除失败", 2);
          }
        }, err => {});
      }, "操作提示", function () {
        //取消时不操作
      });
    },
    toOpenBindPark(row, modalName, treeId) { //打开绑定停车场modal
      this.bindOperator.operatorId = row.id;
      this.toOpenModal(modalName);
      this.initParkTree(treeId);
    },
    initParkTree(treeId) { //初始化绑定停车场树
      let self = this;
      API.platform_manage.GetParkGroupPark({
        "operatorId": this.bindOperator.operatorId
      }).then(res => {
        if (res.status != 1) {
          self.showToast("获取停车场树失败", 2);
        } else {
          let param = {
            "parkList": res.data
          };
          API.platform_manage.GetAreaParkTree({
            "operatorId": self.bindOperator.operatorId,
            "isAll": false
          }).then(res => {
            let data = res.data;
            self.noAuthText = null;
            if (res.status != 1 || data == null) {
              self.noAuthText = "上级运营商没有权限";
              // self.showToast("上级运营商没有权限", 2);
            } else {
              var nodes = data && data.children ? data.children : [];

              // var nodes = [];
              if (nodes.length == 0) {
                self.noAuthText = "该运营商没有授权停车场";
                // self.showToast("该运营商没有授权停车场", 2);
                return;
              }
              var settings = {
                check: {
                  enable: true
                },
                data: {
                  simpleData: {
                    enable: true
                  }
                },
                view: {
                  showIcon: false,
                  showLine: false,
                }
              };
              $.fn.zTree.destroy(treeId);
              $.fn.zTree.init($("#" + treeId), settings, nodes);
              var treeObj = $.fn.zTree.getZTreeObj(treeId);
              for (var i = 0; i < param.parkList.length; i++) {
                if (param.parkList[i] != null && param.parkList[i].parkingId != null) {
                  var node = treeObj.getNodeByParam("value", param.parkList[i].parkingId);
                  if (node) {
                    // if (node.getParentNode() && !node.getParentNode().open) {
                    //   treeObj.expandNode(node.getParentNode(), true, true, true);
                    // }
                    treeObj.checkNode(node, true, true);
                  }
                }
              }
              treeObj.expandAll(true);
            }
          }, err => {});
        }
      }, err => {});
    },
    saveBindPark(treeId, modalName) {
      let self = this;
      var tree = $.fn.zTree.getZTreeObj(treeId);
      var nodes = tree.getCheckedNodes(true);
      var parkList = new Array();
      var params = null;
      for (var i = 0; i < nodes.length; i++) {
        if (!nodes[i].isArea) {
          parkList.push(nodes[i].value);
        }
      }
      params = {
        'operatorId': self.bindOperator.operatorId,
        'parkIds': parkList.join(",")
      };

      API.platform_manage.SaveBindPark(params).then(res => {
        let sta = res.status;
        if (res.status == 1) {
          self.closed(modalName);
          self.showToast("绑定成功", 1);
        } else {
          self.showToast("绑定失败", 2);
        }
      }, err => {});
    },
    toOpenPwdEdit(row, modalName) { //打开密码修改
      clearObject(this.pwdForm);
      this.pwdForm.name = row.name;
      this.pwdForm.loginId = row.loginId;
      this.toOpenModal(modalName, 1);
    },
    editOperatorPwd(formName, modalName) { //修改密码
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false;
        } else {
          API.platform_manage.EditOperatorPwd(this.pwdForm).then(res => {
            let sta = res.status;
            if (res.status == 1) {
              this.closed(modalName);
              this.getList();
              this.showToast("修改成功", 1);
            } else {
              this.showToast("修改失败", 2);
            }
          }, err => {});
        }
      });
    },
    removeLicenseImg(file, fileList) { //删除上传的运营牌照照片
      this.licenseImg = [];
      this.operaotrForm.licenseImgBase64 = "";
      this.operaotrForm.licenseImgName = "";
    },
    beforeUploadLicenseImg(file) { //运营牌照照片上传前处理
      let self = this;
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        this.licenseImg = [{
          "name": file.name,
          "url": "#"
        }];
        var res = e.target.result.replace("data:image/png;base64,", "");
        res = res.replace("data:image/jpg;base64,", "");
        res = res.replace("data:image/jpeg;base64,", "");
        self.operaotrForm.licenseImgBase64 = res;
        self.operaotrForm.licenseImgName = file.name;
      }
    },
    uploadLicenseImg(obj) { //运营牌照照片上传，实际是转化为base64编码数据
      //不做处理
      console.log(obj);
    },
    removeLegalIdentityImg(file, fileList) { //删除上传的运营牌照照片
      this.legalIdentityImg = [];
      this.operaotrForm.legalIdentityImgBase64 = "";
      this.operaotrForm.legalIdentityImgName = "";
    },
    beforeUploadLegalIdentityImg(file) { //运营牌照照片上传前处理
      let self = this;
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        this.legalIdentityImg = [{
          "name": file.name,
          "url": "#"
        }];
        var res = e.target.result.replace("data:image/png;base64,", "");
        res = res.replace("data:image/jpg;base64,", "");
        res = res.replace("data:image/jpeg;base64,", "");
        self.operaotrForm.legalIdentityImgBase64 = res;
        self.operaotrForm.legalIdentityImgName = file.name;
      }
    },
    uploadLegalIdentityImg(obj) { //运营牌照照片上传，实际是转化为base64编码数据
      //不做处理
    },
    removeAllUploadImg() {
      this.legalIdentityImg = [];
      this.operaotrForm.legalIdentityImgBase64 = "";
      this.operaotrForm.legalIdentityImgName = "";
      this.licenseImg = [];
      this.operaotrForm.licenseImgBase64 = "";
      this.operaotrForm.licenseImgName = "";
    },
    toOpenOperatorAdd(modalName) { //打开新增
      this.removeAllUploadImg();
      this.operaotrFormStatus = 'add';
      clearObject(this.operaotrForm);
      this.toOpenModal(modalName);
    },
    toOpenOperatorEdit(row, modalName) { //打开编辑
      this.removeAllUploadImg();
      this.operaotrFormStatus = 'edit';
      copyObjBySelf(this.operaotrForm, row);
      // if (this.operaotrForm.legalIdentityImg) {
      //   this.operaotrForm.legalIdentityImg = "/mgr" + this.operaotrForm.legalIdentityImg
      // }
      // if (this.operaotrForm.licenseImg) {
      //   this.operaotrForm.licenseImg = "/mgr" + this.operaotrForm.licenseImg
      // }
      this.operaotrForm.oldName = row.name;
      this.toOpenModal(modalName);
    },
    toOpenOperatorLook(row, modalName) { //打开查看
      this.removeAllUploadImg();
      this.operaotrFormStatus = 'look';
      copyObjBySelf(this.operaotrForm, row);
      this.toOpenModal(modalName);
    },
    cannotEdit(actionss) { //判断该元素是否可用，actionss代表操作，与operaotrFormStatus相等时，返回true
      let result = false;
      if (this.operaotrFormStatus == actionss) {
        result = true;
      }
      return result;
    },
    toOpenSelectAreaModal(treeId, modalName) { //打开区域选择树
      this.toOpenModal(modalName);
      this.initAreaTree(treeId);
    },
    initAreaTree(treeId) { //初始化绑定停车场树
      let self = this;
      API.platform_manage.GetOperatorAreaTree().then(res => {
        if (res.status != 1 || res.data == null) {
          self.showToast("暂时没有区域可选", 2);
        } else {
          var nodes = res.data;
          var settings = {
            check: {
              enable: true,
              chkboxType: {
                "Y": "",
                "N": ""
              }
            },
            data: {
              simpleData: {
                enable: true
              }
            },
            view: {
              showIcon: false,
              showLine: false,
            },
            async: {
              autoParam: ['value'],
              dataType: 'text',
              enable: true,
              type: 'get',
              url: '/mgr/operator/getAreaTree.do'
            }
          };
          $.fn.zTree.destroy(treeId);
          var treeObj = $.fn.zTree.init($("#" + treeId), settings, nodes);
          // treeObj.expandAll(true);
        }
      }, err => {});
    },
    selectArea(treeId, modalName) { //获取区域树所选择的值
      var self = this,
        nodes = [];
      var treeObj = $.fn.zTree.getZTreeObj(treeId);
      nodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点
      if (nodes.length <= 0) {
        this.showToast('请至少选择一个区域', 2);
        return;
      }
      if (nodes != null) {
        var areaList = nodes,
          areaId = '',
          areaName = '';
        for (var i = 0; i < areaList.length; i++) {
          if (areaId == null) {
            areaId = areaList[i].value;
            areaName = areaList[i].name;
          } else {
            areaId = areaId + "," + areaList[i].value;
            areaName = areaName + "," + areaList[i].name;
          }
        }
        self.operaotrForm.areaId = areaId.replace(/^,/, "").replace(/,$/, "");
        self.operaotrForm.areaName = areaName.replace(/^,/, "").replace(/,$/, "");
      }
      this.closed(modalName);
    },
    saveOperatorForm(formName, modalName) { //保存运营商
      let params = this.operaotrForm;
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false;
        } else {
          API.platform_manage.SaveOperatorData(this.operaotrForm).then(res => {
            let sta = res.status;
            if (res.status == 1) {
              this.closed(modalName);
              this.getList();
              this.showToast("操作成功", 1);
            } else {
              this.showToast("操作失败", 2);
            }
          }, err => {});

        }
      });
    },
    filterMultiCheck(selectionArr) { //必须定义获取多列的方法
      let result = [];
      selectionArr.map((item) => {
        result.push(item.id);
      });
      return result;
    }

  }
}
